//
//  RCSBrowserVideoViewController.m
//  Decathlon
//
//  Created on 15-5-12.
//  Copyright (c) 2015年. All rights reserved.
//

#import "RCSBrowserVideoViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVAsset.h>
#import <AssetsLibrary/AssetsLibrary.h>
//#import "RCSVideoPickerDelegate.h"
//#import "RcSFileUtil.h"
//#import "RCSChatViewController.h"
//#import "RCSChatViewAuxiliary.h"
//#import "RCSBaseAlertView.h"
#import "UIColor+Additions.h"
#import "FTAlbumPhotoControllerDelegate.h"



#define kPlayBtnWidth 28
#define KFootViewHeight 50
#define KTagActionSheetSelectVideo 500

@interface RCSBrowserVideoViewController ()
{
    MPMoviePlayerViewController *_playViewController;
    UIImageView                 *_thumbImageView;
    UIButton                    *_playButton;
    ALAsset                     *_videoALAsset;
}

@end

@implementation RCSBrowserVideoViewController

-(id)initWithALAsset:(ALAsset *)videoALAsset
{
    if (self = [super init])
    {
        _videoALAsset = videoALAsset;
    }
    return self;
}

-(void)dealloc
{
    _thumbImageView = nil;
    _playButton = nil;
    _videoALAsset = nil;
    self.delegate = nil;
}

-(void)loadView
{
    [super loadView];
    
    [self initBrowserVideoUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //[self setStrNavTitle:@"视频预览"];
}

-(void)initBrowserVideoUI
{
    CGSize size = [UIScreen mainScreen].bounds.size;
    //缩略图
    _thumbImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, CGRectGetHeight(self.view.frame)-KFootViewHeight)];
    _thumbImageView.backgroundColor = [UIColor clearColor];
    _thumbImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _thumbImageView.image = [UIImage imageWithCGImage:_videoALAsset.thumbnail];
    _thumbImageView.contentMode = UIViewContentModeScaleAspectFill;
    [_thumbImageView.layer setMasksToBounds:YES];
    [self.view addSubview:_thumbImageView];
    
    //播放按钮
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playButton addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
    _playButton.backgroundColor = [UIColor clearColor];
    _playButton.frame = CGRectMake((size.width-kPlayBtnWidth) / 2,
                                   (size.height - kPlayBtnWidth -KFootViewHeight - 64) / 2,
                                   kPlayBtnWidth,
                                   kPlayBtnWidth);
    [_playButton setImage:[UIImage imageNamed:@"message_play_disabled"] forState:UIControlStateNormal];
    [self.view addSubview:_playButton];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, size.height-KFootViewHeight, size.width, KFootViewHeight)];
    footView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    footView.backgroundColor = [UIColor darkGrayColor];
    [self.view addSubview:footView];
    
    long long fileSize = [[_videoALAsset defaultRepresentation] size];
    fileSize = fileSize / 1024;//K
    NSString *unit = @"K";
    if (fileSize >= 1024)
    {
        fileSize = fileSize / 1024;
        unit = @"M";
    }
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 200, KFootViewHeight)];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.text = [NSString stringWithFormat:@"视频大小:%lld%@",fileSize,unit];
    [footView addSubview:titleLab];
    
    UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sendButton.frame = CGRectMake(size.width - 65, 0, 60, KFootViewHeight);
    [sendButton addTarget:self action:@selector(sendVideo) forControlEvents:UIControlEventTouchUpInside];
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    sendButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [sendButton setTitleColor:[UIColor rcsColorWithHexString:@"0fc381"] forState:UIControlStateNormal];
    sendButton.backgroundColor = [UIColor clearColor];
    [footView addSubview:sendButton];
}

-(void)sendVideo
{
    NSMutableArray* selectVideoArray = [[NSMutableArray alloc] init];
    
    NSString *uti = [[_videoALAsset defaultRepresentation] UTI];
    NSURL *videoURL = [[_videoALAsset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
    
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithCapacity:4];
//  [dict setValue:[NSNumber numberWithInteger:self.selectSendType] forKey:KPickerMediaSelectSendType];
//  [dict setValue:[NSNumber numberWithInteger:SV_VideoFileTypeSend] forKey:KPickerMediaType];
    [dict setValue:[NSString stringWithFormat:@"%@",videoURL] forKey:KPickerMediaUrl];
    [dict setValue:[NSNumber numberWithLongLong:[[_videoALAsset defaultRepresentation] size]] forKey:KPickerMediaSize];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectedVideoDictionary:pickController:videoData:)])
    {
        //////////////////
        @autoreleasepool
        {
            NSUInteger size = (NSUInteger)[_videoALAsset.defaultRepresentation size];
            uint8_t *buff = (uint8_t*)malloc(size);
            NSError *err = nil;
            [_videoALAsset.defaultRepresentation getBytes:buff fromOffset:0 length:size error:&err];
            
            //不需要再调用free()
            NSData *originScreenImgData = [NSData dataWithBytesNoCopy:buff length:size freeWhenDone:YES];
            if (originScreenImgData)
            {
                [selectVideoArray addObject:originScreenImgData];
            }
        }
        
        [self.delegate selectedVideoDictionary:dict pickController:self videoData:selectVideoArray];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (self.isComeFromWiFi)
    {
        //[[NSNotificationCenter defaultCenter] postNotificationName:MSG_FileTransferWhenCallNotification object:nil];
    }
    else
    {
         [self dismissViewControllerAnimated:NO completion:nil];
    }
}

-(void)showTipWithMessage:(NSString *)tipMsg
{
    //[self.view rcsmakeToast:tipMsg duration:2.0 position:@"center"];
}


-(void)leftButtonPressed:(id)action
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)playVideo
{
    _playViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[_videoALAsset valueForProperty:ALAssetPropertyAssetURL]];
    MPMoviePlayerController* player = [_playViewController moviePlayer];
    player.scalingMode = MPMovieScalingModeAspectFit;
    player.controlStyle = MPMovieControlStyleFullscreen;
    // 注册一个播放结束的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(myMovieFinishedCallback:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:player];
    [self.navigationController presentViewController:_playViewController animated:YES completion:nil];
    [player play];
}

/*
 @method 当视频播放完毕释放对象
 */
-(void)myMovieFinishedCallback:(NSNotification*)notify
{
    //视频播放对象
    MPMoviePlayerViewController* theMovie = [notify object];
    //销毁播放通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:theMovie];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
